$(function() {
    var showData = {};
    var pageNum = 1;
    getData(pageNum);

    (function() {
        var Router = function() {
            this.routes = {}; //用来保存路由
            this.curUrl = ''; //获取当前的hash
        }
        Router.prototype.init = function() { //监听路由变化
            window.addEventListener('hashchange', this.reloadPage.bind(this));
        }
        Router.prototype.reloadPage = function() {
            this.curUrl = location.hash.substring(1) || '/';
            this.routes[this.curUrl]();
        }
        Router.prototype.map = function(key, callback) { //保存路由对应的函数
            this.routes[key] = callback;
        }
        window.Router = Router;
    })();

    var oRouter = new Router();
    oRouter.init();
    oRouter.map('/', function() {
        // var oSidebar = document.querySelector("info");
        // oSidebar.innerHTML = 'ghostwu提供html,css,javascript从0基础到精通系列课程，只要会开关机，就能学会';
        $("#iframepage").attr('src', 'view/info.html');
    });
    oRouter.map('/test', function() {
        // var oSidebar = document.querySelector("sidebar");
        // oSidebar.innerHTML = 'ghostwu提供html5从入门到精通的课程';
        $("#iframepage").attr('src', 'view/test.html');
    });
    oRouter.map('/info', function() {
        // var oSidebar = document.querySelector("sidebar");
        // oSidebar.innerHTML = 'ghostwu提供html5从入门到精通的课程';
        $("#iframepage").attr('src', 'view/info.html');
    });
    oRouter.map('/about', function() {
        // var oSidebar = document.querySelector("sidebar");
        // oSidebar.innerHTML = 'ghostwu提供html5从入门到精通的课程';
        $("#iframepage").attr('src', 'view/about.html');
    });
    oRouter.map('/canvas', function() {
        // var oSidebar = document.querySelector("sidebar");
        // oSidebar.innerHTML = 'ghostwu提供html5从入门到精通的课程';
        $("#iframepage").attr('src', 'view/canvas2.html');
    });

    $("#btn_add").click(function(event) {
        /* Act on the event */
        $('#addModal').modal('show');
    });

    $("#btn_edit").click(function(event) {
        /* Act on the event */
        var selected = $('#tb_departments').bootstrapTable("getSelections");
        console.log("selected:", selected);
        if (selected.length <= 0) {
            alert("请选择需要修改的数据！！！");
            return;
        } else if (selected.length > 1) {
            alert("一次只能修改一条数据！！！");
            return;
        } else {
            editUser(selected[0]);
            $('#editModal').modal('show');
        }
    });

    $("#btn_delete").click(function(event) {
        /* Act on the event */
        var selected = $('#tb_departments').bootstrapTable("getSelections");
        if (selected.length <= 0) {
            alert("请选择需要删除的数据！！！");
        } else {
            if (confirm("确定删除选中的 " + selected.length + " 条数据")) {
                for (var i = 0; i < selected.length; i++) {
                    var userId = selected[i].userid;
                    delUser(userId);
                }
                pageNum = $('#tb_departments').bootstrapTable('getOptions').pageNumber;
                $('#tb_departments').bootstrapTable('destroy');
                getData(pageNum);
            } else {
                return;
            }
        }
    });

    $("#editSubmit").click(function(event) {
        /* Act on the event */
        var userName = $("input[name='editName']").val();
        var userId = $("input[name='editId']").val();
        var passwd = $("input[name='editPasswd']").val();
        var company = $("input[name='editCompany']").val();
        var age = $("input[name='editAge']").val();
        var sex = $("input[name='editSex']:checked").val();
        var url = "http://127.0.0.1:8080/friend/webuser/updateUser";
        console.log(userName, " : ", " : ", userId, " : ", passwd, " : ", company, " : ", age, " : ", sex, " : ", url);
        operationUser(userName, userId, passwd, company, age, sex, url);
        pageNum = $('#tb_departments').bootstrapTable('getOptions').pageNumber;
        // console.log("PageNum: ", pageNum);
        $('#tb_departments').bootstrapTable('destroy');
        getData(pageNum);
        $("#editModal").modal('hide');
    });

    $("#addSubmit").click(function(event) {
        /* Act on the event */
        var userId = $("input[name='addId']").val();
        var userName = $("input[name='addName']").val();
        var passwd = $("input[name='addPasswd']").val();
        var company = $("input[name='addCompany']").val();
        var age = $("input[name='addAge']").val();
        var sex = $("input[name='addSex']:checked").val();
        var url = "http://127.0.0.1:8080/friend/webuser/addUser";
        console.log(userName, " : ", userId, " : ", passwd, " : ", company, " : ", age, " : ", sex, " : ", url);
        operationUser(userName, userId, passwd, company, age, sex, url); //连接后端，修改数据库
        pageNum = $('#tb_departments').bootstrapTable('getOptions').pageNumber;
        $('#tb_departments').bootstrapTable('destroy'); //清除表格
        getData(pageNum);
        $('#addModal').modal('hide');
    });

    $("#btn_refresh").click(function(event) {
        /* Act on the event */
        pageNum = $('#tb_departments').bootstrapTable('getOptions').pageNumber;
        $('#tb_departments').bootstrapTable('destroy'); //清除表格
        getData(pageNum);
    });

    // 关闭模态框清除内容
    // $('#addModal').on('hidden.bs.modal', function() {
    //     $("#addModal form")[0].reset();
    // });

    $('body').on('hidden.bs.modal', '.modal', function() {
        $("#addModal form")[0].reset();
    });

    function tableView(data, pageNum) {
        /* Act on the event */
        $('#tb_departments').bootstrapTable({
            data: data,
            toolbar: '#toolbar', //工具按钮用哪个容器
            striped: true, //是否显示行间隔色
            pagination: true, //是否显示分页（*）
            // sortable: true, //是否启用排序
            // sortOrder: "asc", //排序方式
            // queryParams: '', //传递参数（*）
            sidePagination: "client", //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: pageNum, //初始化加载第一页，默认第一页
            pageSize: 10, //每页的记录行数（*）
            pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
            search: true, //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            // strictSearch: true,
            showColumns: true, //是否显示所有的列
            // showRefresh: true, //是否显示刷新按钮
            clickToSelect: true, //是否启用点击选中行
            // height: 520, //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            // uniqueId: "ID", //每一行的唯一标识，一般为主键列
            // showToggle: true, //是否显示详细视图和列表视图的切换按钮
            columns: [{
                field: 'checked',
                checkbox: true,
                // radio: true
            }, {
                field: 'userid',
                title: '用户ID'
            }, {
                field: 'username',
                title: '用户名'
            }, {
                field: 'password',
                title: '密码'
            }, {
                field: 'company',
                title: '公司'
            }, {
                field: 'age',
                title: '年龄'
            }, {
                field: 'sex',
                title: '性别'
            }],
            onDblClickCell: editUser
        });
    }

    function getData(pageNum) {
        $.ajax({
            url: "http://127.0.0.1:8080/friend/webuser/getAllUser",
            method: "post",
            dataType: 'json',
            async: false,
            data: {},
            success: function(res) {
                console.log("post res: ", res);
                showData = res.data2;
                tableView(showData, pageNum);
            },
            error: function(error) {
                console.log("post error: ", error)
            }
        });
    };

    function editUser(row) {
        console.log("row :", row);
        var sex;
        if (row.sex == "男") {
            $("input[type='radio'][value=0]").attr("checked", false);
            $("input[type='radio'][value=1]").attr("checked", true);
        } else {
            $("input[type='radio'][value=1]").attr("checked", false);
            $("input[type='radio'][value=0]").attr("checked", true);
        }
        $("input[name='editId']").val(row.userid);
        $("input[name='editName']").val(row.username);
        $("input[name='editPasswd']").val(row.password);
        $("input[name='editCompany']").val(row.company);
        $("input[name='editAge']").val(row.age);

        $('#editModal').modal('show');
    }

    function operationUser(userName, userId, passwd, company, age, sex, url) {
        $.ajax({
            url: url,
            method: "post",
            dataType: 'json',
            async: false,
            data: {
                "id": userId,
                "username": userName,
                "password": passwd,
                "company": company,
                "age": age,
                "sex": sex
            },
            success: function(res) {
                console.log("post res: ", res);
                alert(res.msg);
            },
            error: function(error) {
                console.log("post error: ", error);
            }
        });
    }

    function delUser(userid) {
        $.ajax({
            url: "http://127.0.0.1:8080/friend/webuser/delUser",
            method: "post",
            dataType: 'json',
            async: false,
            data: {
                "id": userid
            },
            success: function(res) {
                // alert(res.msg);
                console.log("post res: ", res);
            },
            error: function(error) {
                console.log("post error: ", error)
            }
        });
    }
});